package com.pengshun.modules.api.transport.service.impl;

import com.pengshun.modules.api.coal.repository.MerchantRepository;
import com.pengshun.modules.api.coal.util.CommonUtil;
import com.pengshun.modules.api.mapper.SystemMapper;
import com.pengshun.modules.api.mapper.TransportMapper;
import com.pengshun.modules.api.order.repository.OrderAllotTransportRepository;
import com.pengshun.modules.api.system.domain.District;
import com.pengshun.modules.api.transport.dto.*;
import com.pengshun.modules.api.transport.repository.TransportRepository;
import com.pengshun.modules.api.transport.service.TransportService;
import com.pengshun.modules.api.transport.service.mapstruct.TransportTodo;
import com.pengshun.modules.common.*;
import com.pengshun.modules.domain.*;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.context.MessageSource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.awt.image.BufferedImage;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import static com.pengshun.modules.api.util.QRCodeUtils.createImage;
import static com.pengshun.modules.api.util.QRCodeUtils.upoos;

@Service
@RequiredArgsConstructor
public class TransportServiceImpl implements TransportService {


    private final TransportMapper transportMapper;
    private final SystemMapper systemMapper;
    private final MerchantRepository merchantRepository;
    private final TransportRepository transportRepository;
    private final TransportTodo transportTodo;
    private final OrderAllotTransportRepository orderAllotTransportRepository;
    private final MessageSource messageSource;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public BaseResult save(TransportDto para) throws Exception {
//        if(para.getOilProportion()+para.getCashProportion()!=10){
//            return new BaseResult(1, messageSource.getMessage("TransportServiceImpl.save.proportion", null, Locale.CHINA));
//        }
        if (para.getOrderAllotTransportId() != null) {
            Transport transport=transportRepository.findByOrderAllotTransportId(para.getOrderAllotTransportId());
            if(transport!=null){
                return new BaseResult(1, messageSource.getMessage("TransportServiceImpl.save.same", null, Locale.CHINA));
            }
            //说明是货源订单发布    发布运费不能大于分配运费
            OrderAllotTransport allotTransport = orderAllotTransportRepository.findById(para.getOrderAllotTransportId()).orElseGet(OrderAllotTransport::new);
            if (para.getFreightPrice().compareTo(allotTransport.getFreight()) == 1) {
                return new BaseResult(1, messageSource.getMessage("TransportServiceImpl.save.freight.big", null, Locale.CHINA));
            }
            //更新发布时间
            allotTransport.setStatus(3);
            allotTransport.setIssueTime(new Date());
            orderAllotTransportRepository.save(allotTransport);
            para.setOrderAllotTransportId(para.getOrderAllotTransportId());
            para.setOrderId(allotTransport.getOrderId());
        }
        Merchant merchant = merchantRepository.findByUserId(para.getUserId());
        para.setMerchantName(merchant.getName());
        para.setTotalNumber(para.getWeight());
        para.setMerchantId(merchant.getId());
        para.setCreateTime(new Date());
        para.setStatus(0);
        para.setInfoType(para.getInfoFee() == null ? 0 : 1);
        para.setIsShow(1);
        para.setIsPremium(0);

        District district = systemMapper.selectDstrictDetil(para.getShipDistrictAdcode());
        District district1 = systemMapper.selectDstrictDetil(para.getReceiveDistrictAdcode());

        para.setTransportNo("PT" + CommonUtil.getFourRandom());
        para.setShipCityAdcode(district == null ? null : district.getCityId() + "");
        para.setReceiveCityAdcode(district1 == null ? null : district.getCityId() + "");
        //设置费用 如果为空则改为0
        para.setInfoFee(para.getInfoFee() == null ? new BigDecimal(0) : para.getInfoFee());
        para.setLoadFee(para.getLoadFee() == null ? new BigDecimal(0) : para.getLoadFee());
        para.setUnloadFee(para.getUnloadFee() == null ? new BigDecimal(0) : para.getUnloadFee());
        para.setPoundsFee(para.getPoundsFee() == null ? new BigDecimal(0) : para.getPoundsFee());
        para.setOtherFee(para.getOtherFee() == null ? new BigDecimal(0) : para.getOtherFee());


        Transport tran = transportTodo.toEntity(para);
        tran.setShipLngX(para.getShipLongitude());
        tran.setShipLatY(para.getShipLatitude());
        tran.setReceiveLngX(para.getReceiveLongitude());
        tran.setReceiveLatY(para.getReceiveLatitude());
        Transport transport = transportRepository.save(tran);


//        if (para.getIsAppoint() == 1) {
//            if (para.getTransportAssigns() != null && para.getTransportAssigns().size() > 0) {
//                for (TransportAssign assign : para.getTransportAssigns()) {
//                    assign.setTransportId(transport.getId());
//                }
//                //指定运输公司表添加数据
//                transportMapper.insertAssignsList(para.getTransportAssigns());
//            }
//        }
        return new BaseResult(0, messageSource.getMessage("TransportServiceImpl.save.success", null, Locale.CHINA));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public BaseResult update(TransportDto para) throws Exception {
        Transport transport = transportRepository.findById(para.getId()).orElseGet(Transport::new);
        //状态(0未发布，1审核中，2已发布，3已驳回,4已完成5已删除)

        //审核中 、已发布、已完成、已删除 不能修改
        if (transport.getStatus().equals(TransportStatus.ONE_STATUS) || transport.getStatus().equals(TransportStatus.TWO_STATUS)
                || transport.getStatus().equals(TransportStatus.FOUR_STATUS) || transport.getStatus().equals(TransportStatus.FIVE_STATUS)) {
            return new BaseResult(0, messageSource.getMessage("TransportServiceImpl.update.status", null, Locale.CHINA));
        }
        BeanUtils.copyProperties(para, transport, UpdateUtil.getNullPropertyNames(para));
        transportRepository.save(transport);
        para.setUpdateTime(new Date());
        return new BaseResult(0, messageSource.getMessage("TransportServiceImpl.update.success", null, Locale.CHINA));
    }

    @Override
    public BaseResult detil(TransportDto para) {
        TransportDto dto = transportMapper.getTransportDetilById(para.getId());

        dto.setInfoFee(dto.getInfoFee() == null ? new BigDecimal(0) : dto.getInfoFee());
        dto.setLoadFee(dto.getLoadFee() == null ? new BigDecimal(0) : dto.getLoadFee());
        dto.setUnloadFee(dto.getUnloadFee() == null ? new BigDecimal(0) : dto.getUnloadFee());
        dto.setPoundsFee(dto.getPoundsFee() == null ? new BigDecimal(0) : dto.getPoundsFee());
        dto.setOtherFee(dto.getOtherFee() == null ? new BigDecimal(0) : dto.getOtherFee());
        return new BaseResult(0, dto);
    }

    @Override
    public BaseResult list(TransportDto dto) {
        int page = (dto.getPage()) * dto.getSize();
        List<TransportDto> list = transportMapper.getTransportListByStatus(page < 0 ? 0 : page, dto.getSize(), dto.getStatus(), dto.getUserId());
        return new BaseResult(0, list);
    }

    @Override
    public BaseResult updateStatus(TransportDto para) throws Exception {
        Transport transport = transportRepository.findById(para.getId()).orElseGet(Transport::new);
        String message = "";
        if (para.getStatus() != null) {
            if (para.getStatus() == 1 && transport.getStatus() == 1) {
                //审核中无法发布
                return new BaseResult(1, messageSource.getMessage("TransportServiceImpl.updateStatus.status.err", null, Locale.CHINA));
            }
            if (para.getStatus() == 5 && transport.getStatus() == 2) {
                //已发布无法删除
                return new BaseResult(1, messageSource.getMessage("TransportServiceImpl.updateStatus.status.show", null, Locale.CHINA));
            }
            transport.setStatus(para.getStatus());
            if (para.getStatus() == 1) {
                transport.setReleaseTime(new Date());
                //发布
                message = messageSource.getMessage("TransportServiceImpl.updateStatus.status.check", null, Locale.CHINA);
                //生成二维码
                BufferedImage image=createImage("2,"+para.getId());
                String url=upoos(image);
                transport.setQrCode(url);
            }
            if (para.getStatus() == 5) {
                //删除
                message = messageSource.getMessage("TransportServiceImpl.updateStatus.status.delete", null, Locale.CHINA);
                if(transport.getOrderAllotTransportId()!=null){
                    //更改货源订单分配状态为 未发布
                    OrderAllotTransport allotTransport=orderAllotTransportRepository.findById(transport.getOrderAllotTransportId()).orElseGet(OrderAllotTransport::new);
                    allotTransport.setStatus(OrderCommon.ALLOT_STATEUS_TWO);
                    orderAllotTransportRepository.save(allotTransport);
                }
            }
        }

        if (para.getIsShow() != null) {
            transport.setIsShow(para.getIsShow());
            if (para.getIsShow() == 0) {
                //下架
                message = messageSource.getMessage("TransportServiceImpl.updateStatus.status.down", null, Locale.CHINA);
            }
            if (para.getIsShow() == 1) {
                //上架
                message = messageSource.getMessage("TransportServiceImpl.updateStatus.status.up", null, Locale.CHINA);
            }
        }
        transportRepository.save(transport);
        return new BaseResult(0, message);
    }

    @Override
    public BaseResult selectTakeList(TransportDto para) {
        int page = (para.getPage()) * para.getSize();
        List<TakeCarriageDto> list = transportMapper.selectTakeList(page < 0 ? 0 : page, para.getSize(), para.getId(),para.getStatus());
        return new BaseResult(0, list);
    }

    @Override
    public BaseResult settList(TransportDto para) {
        int page = (para.getPage()) * para.getSize();
        List<TransportSettDto> list = transportMapper.settList(page < 0 ? 0 : page, para.getSize(), para.getId(),para.getStatus());
        return new BaseResult(0, list);
    }
}
